package com.jd.ty.service;

import java.util.Date;
import java.util.List;

import com.jd.ty.dao.DictionaryDAO;
import com.jd.ty.dao.EmployeeDAO;
import com.jd.ty.dao.RoleDAO;
import com.jd.ty.dao.UserDAO;
import com.jd.ty.dao.constant.QueryConstants;
import com.jd.ty.dao.util.HqlCriterions;
import com.jd.ty.pojo.BankCard;
import com.jd.ty.pojo.Contract;
import com.jd.ty.pojo.Credentials;
import com.jd.ty.pojo.Dictionary;
import com.jd.ty.pojo.Employee;
import com.jd.ty.pojo.Experience;
import com.jd.ty.pojo.Role;
import com.jd.ty.pojo.User;
import com.jd.ty.service.exception.ErrorCode;
import com.jd.ty.service.exception.ErrorMessage;
import com.jd.ty.service.exception.ServiceException;
import com.jd.ty.util.CommonUtils;
import com.jd.ty.util.Pager;

public class EmployeeService {

	private EmployeeDAO employeeDAO;

	private UserDAO userDAO;
	private RoleDAO roleDAO;
	private DictionaryDAO dictionaryDAO;

	@SuppressWarnings("unchecked")
	public List<Employee> getList(String filter) {
		return employeeDAO.getByQuery(filter);
	}

	@SuppressWarnings("unchecked")
	public List<Employee> getList(String filter, String sort) {
		return employeeDAO.getByQuery(filter, sort);
	}

	@SuppressWarnings("unchecked")
	public List<Employee> getList(Pager pager, String filter, String sort) {
		return employeeDAO.getByQuery(pager, filter, sort);
	}

	public Employee get(long id) {
		return (Employee) employeeDAO.getById(id);
	}

	public Employee load(long id) {
		Employee employee = (Employee) employeeDAO.loadById(id);

		employeeDAO.initialize(employee.getUserInfo());

		return employee;
	}

	public void add(final Employee employee) throws ServiceException {
		HqlCriterions hc = new HqlCriterions();
		User user = employee.getUserInfo();
		hc.and(QueryConstants.User.loginId, user.getLoginId(),
				QueryConstants.EQ);

		if (userDAO.getCountByQuery(hc.getHqlString()) > 0) {
			String errMsg = CommonUtils.formatString(
					ErrorMessage.DUPLICATION_ENTITY_USER,
					new String[] { employee.getUserInfo().getLoginId() });
			throw new ServiceException(ErrorCode.DUPLICATION_ENTITY, errMsg);
		}
		hc.clear();
		hc.and(QueryConstants.Employee.EMPLOYEE_NAME, employee
				.getEmployeeName(), QueryConstants.EQ);
		if (employeeDAO.getCountByQuery(hc.getHqlString()) > 0) {
			String errMsg = CommonUtils.formatString(
					ErrorMessage.DUPLICATION_ENTITY_EMPLOYEE,
					new String[] { employee.getEmployeeName() });
			throw new ServiceException(ErrorCode.DUPLICATION_ENTITY, errMsg);
		}

		setDictionary(employee);
		setRole(user);
		user.setCreatedDate(new Date());
		user.setLastModified(new Date());
		employeeDAO.add(employee);

	}

	private void setRole(User user) {
		Role role = (Role) roleDAO.loadById(user.getRole().getRoleId());
		user.setRole(role);
	}

	private void setDictionary(Employee employee) {
		Long id = employee.getDegree().getDictionaryId();
		if (id != null) {

			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setDegree(diction);
		}
		id = employee.getDepartment().getDictionaryId();
		if (id != null) {

			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setDepartment(diction);
		}
		id = employee.getSocialStatus().getDictionaryId();
		if (id != null) {

			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSocialStatus(diction);
		}
		if (null == employee.getPosition()) {
			employee.setPosition(null);
		} else {
			id = employee.getPosition().getDictionaryId();
			if (id != null) {
				Dictionary position = (Dictionary) dictionaryDAO.loadById(id);
				employee.setPosition(position);
			}
		}
		// Added at 7/Aug/2011
		id = employee.getSex().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSex(diction);
		}
		id = employee.getRegisteredResidenceType().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setRegisteredResidenceType(diction);
		}
		/*
		id = employee.getSalary().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSalary(diction);
		}
		*/
		id = employee.getSocialSecurityStatus().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSocialSecurityStatus(diction);
		}
		id = employee.getSocialSecurityType().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSocialSecurityType(diction);
		}
		id = employee.getSocialSecuritySort().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSocialSecuritySort(diction);
		}
		id = employee.getSocialSecurityCardStatus().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSocialSecurityCardStatus(diction);
		}
		id = employee.getHealthSecurityCardStatus().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setHealthSecurityCardStatus(diction);
		}
		/*
		id = employee.getTrainingState().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setTrainingState(diction);
		}
		*/
		id = employee.getMarriagementState().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setMarriagementState(diction);
		}
		id = employee.getSocialSecurityCompany().getDictionaryId();
		if (id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setSocialSecurityCompany(diction);
		}
		id = employee.getUnifiedEntrance().getDictionaryId();
		if(id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setUnifiedEntrance(diction);
		}
		id = employee.getQuitJobPapers().getDictionaryId();
		if(id != null) {
			Dictionary diction = (Dictionary) dictionaryDAO.loadById(id);
			employee.setQuitJobPapers(diction);
		}
	}

	public void update(final Employee employee) throws ServiceException {
		HqlCriterions hc = new HqlCriterions();
		User user = employee.getUserInfo();
		hc.and(QueryConstants.User.loginId, user.getLoginId(),
				QueryConstants.EQ);
		User u = (User) userDAO.getOneByQuery(hc.getHqlString(), true);
		if (u != null) {
			if (u.getUserId().longValue() != user.getUserId().longValue()) {
				String errMsg = CommonUtils.formatString(
						ErrorMessage.DUPLICATION_ENTITY_USER,
						new String[] { employee.getUserInfo().getLoginId() });
				throw new ServiceException(ErrorCode.DUPLICATION_ENTITY, errMsg);
			}
		}
		hc.clear();
		hc.and(QueryConstants.Employee.EMPLOYEE_NAME, employee
				.getEmployeeName(), QueryConstants.EQ);
		hc.and(QueryConstants.Employee.EMPLOYEE_ID, employee.getEmployeeId(),
				QueryConstants.NE);
		if (employeeDAO.getCountByQuery(hc.getHqlString()) > 0) {
			String errMsg = CommonUtils.formatString(
					ErrorMessage.DUPLICATION_ENTITY_EMPLOYEE,
					new String[] { employee.getEmployeeName() });
			throw new ServiceException(ErrorCode.DUPLICATION_ENTITY, errMsg);
		}

		Employee newEmployee = (Employee) employeeDAO.loadById(employee
				.getEmployeeId());
		user.setLastModified(new Date());
		setRole(user);
		setDictionary(employee);

		newEmployee.getUserInfo().setRole(user.getRole());
		newEmployee.getUserInfo().setLoginId(user.getLoginId());
		newEmployee.getUserInfo().setLoginPwd(user.getLoginPwd());
		newEmployee.setEmployeeName(employee.getEmployeeName());
		newEmployee.setEndTimeOfIntern(employee.getEndTimeOfIntern());
		newEmployee.setAddress(employee.getAddress());
		newEmployee.setBirthday(employee.getBirthday());
		newEmployee.setPhoneNumber(employee.getPhoneNumber());
		newEmployee.setHomePhoneNumber(employee.getHomePhoneNumber());
		newEmployee.setPostcode(employee.getPostcode());
		newEmployee.setRegisterTime(employee.getRegisterTime());
		newEmployee.setRemarks(employee.getRemarks());
		newEmployee.setSocialId(employee.getSocialId());
		newEmployee.setTimeOfEmployment(employee.getTimeOfEmployment());
		newEmployee.setTimeOfLeaving(employee.getTimeOfLeaving());
		newEmployee.setDegree(employee.getDegree());
		newEmployee.setDepartment(employee.getDepartment());
		newEmployee.setPosition(employee.getPosition());
		newEmployee.setSocialStatus(employee.getSocialStatus());
		// Added at 7/Aug/2011
		newEmployee.setSex(employee.getSex());
		newEmployee.setEthnic(employee.getEthnic());
		newEmployee.setRegisteredResidenceType(employee
				.getRegisteredResidenceType());
		newEmployee.setBirthPlace(employee.getBirthPlace());
		newEmployee.setAge(employee.getAge());
		newEmployee.setCurrentlyAddress(employee.getCurrentlyAddress());
		newEmployee.setSalary(employee.getSalary());
		newEmployee.setSocialSecurityStatus(employee.getSocialSecurityStatus());
		newEmployee.setSocialSecurityTime(employee.getSocialSecurityTime());
		newEmployee.setSocialSecurityType(employee.getSocialSecurityType());
		newEmployee.setSocialSecuritySort(employee.getSocialSecuritySort());
		newEmployee.setSocialSecurityCardStatus(employee
				.getSocialSecurityCardStatus());
		newEmployee.setHealthSecurityCardStatus(employee
				.getHealthSecurityCardStatus());
		newEmployee.setSocialSecurityCompany(employee
				.getSocialSecurityCompany());
		newEmployee.setUnifiedEntrance(employee.getUnifiedEntrance());
		newEmployee.setQuitJobPapers(employee.getQuitJobPapers());
		newEmployee.setAnnouncedSalary(employee.getAnnouncedSalary());
		newEmployee.setPunishmentRecord(employee.getPunishmentRecord());
		newEmployee.setTrainingState(employee.getTrainingState());
		newEmployee.setMarriagementState(employee.getMarriagementState());
		newEmployee.setBusinessName(employee.getBusinessName());
		newEmployee.setSalaryAmount(employee.getSalaryAmount());
		newEmployee.setChineseBirthday(employee.getChineseBirthday());

		for (Contract contract : newEmployee.getContracts()) {
			employeeDAO.delete(contract);
		}
		for (Contract contract : employee.getContracts()) {
			contract.setEmployee(newEmployee);
		}
		newEmployee.setContracts(employee.getContracts());
		//
		for (Credentials credentials : newEmployee.getCredentials()) {
			employeeDAO.delete(credentials);
		}
		for (Credentials credentials : employee.getCredentials()) {
			credentials.setEmployee(newEmployee);
		}
		newEmployee.setCredentials(employee.getCredentials());
		//
		for (Experience exprience : newEmployee.getExperiences()) {
			employeeDAO.delete(exprience);
		}
		for (Experience exprience : employee.getExperiences()) {
			exprience.setEmployee(newEmployee);
		}
		newEmployee.setExperiences(employee.getExperiences());
		//
		for (BankCard bankCard : newEmployee.getBankCards()) {
			employeeDAO.delete(bankCard);
		}
		for (BankCard bankCard : employee.getBankCards()) {
			bankCard.setEmployee(newEmployee);
		}
		newEmployee.setBankCards(employee.getBankCards());

		employeeDAO.saveOrUpdate(newEmployee);

	}

	public List<Employee> getEmployeeByDepartment(Long departId) {

		HqlCriterions hc = new HqlCriterions();
		hc.and(QueryConstants.Employee.DEPARMENT + "."
				+ QueryConstants.Dictionary.DICTIONARY_ID, departId,
				QueryConstants.EQ);
		List<Employee> employees = employeeDAO.getByQuery(hc.getHqlString());
		return employees;
	}

	public void setEmployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}

	public void delete(Long id) {
		Employee empployee = (Employee) employeeDAO.loadById(id);
		if (empployee != null) {
			employeeDAO.delete(empployee);
		}
	}

	public EmployeeDAO getEmployeeDAO() {
		return employeeDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public DictionaryDAO getDictionaryDAO() {
		return dictionaryDAO;
	}

	public void setDictionaryDAO(DictionaryDAO dictionaryDAO) {
		this.dictionaryDAO = dictionaryDAO;
	}

	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}

}
